<template>
	  <!--  连接-->
	  <view style="margin: 1rem">
	    <h1 style="text-align: center;padding-bottom: 0.5rem">Websocket</h1>
	    <view>
	      <uni-forms ref="form" :modelValue="connection" :rules="rules">
	        <uni-forms-item label="Host" name="host">
	          <uni-easyinput type="text" v-model="connection.host" />
	        </uni-forms-item>
	        <uni-forms-item label="Port" name="port">
	          <uni-easyinput type="text" v-model="connection.port" />
	        </uni-forms-item>
	        <uni-forms-item label="Client ID" name="clientId">
	          <uni-easyinput type="text" v-model="connection.clientId" />
	        </uni-forms-item>
	        <uni-forms-item label="Username" name="username">
	          <uni-easyinput type="text" v-model="connection.username" />
	        </uni-forms-item>
	        <uni-forms-item label="PassWord" name="password">
	          <uni-easyinput type="password" v-model="connection.password" />
	        </uni-forms-item>
	        <uni-forms-item label="Keep Alive" name="connectTimeout">
	          <uni-easyinput type="text" v-model="connection.connectTimeout" />
	        </uni-forms-item>
	        <view>
	          <checkbox-group>
	            <label>
	              <checkbox @click="connection.clean=!connection.clean" :checked="connection.clean" />Clean Session
	            </label>
	          </checkbox-group>
	        </view>
	      </uni-forms>
	      <button type="primary" @click="Connect">Connect</button>
	      <button type="warn" @click="Disconnect">Disconnect</button>

	    </view>
	  </view>
	  <hr>
	  <!--  接收-->
	  <view style="margin: 1rem">
	    <h1 style="text-align: center;padding-bottom: 0.5rem">Messages</h1>
	    <view>
	      <view>主题的信息：</view>
	      <view>
	        <uni-table ref="table"  border stripe >
	          <uni-tr>
	            <uni-th align="center">message</uni-th>

	          </uni-tr>
	          <uni-tr v-for="(item, index) in listmsg" :key="index">
	            <uni-td>{{ item.message }}</uni-td>

	          </uni-tr>
	        </uni-table>
	      </view>
	    </view>
	  </view>
</template>

<script setup>
	import * as mqtt from 'mqtt/dist/mqtt.js';
	import {
		reactive,
		ref,
		onMounted
	} from "vue";

	// https://github.com/mqttjs/MQTT.js#qos
	const qosList = [0, 1, 2];
	let client = ref({
		connected: false
	});
	const listmsg=reactive([])
	const receivedMessages = ref("");
	const subscribedSuccess = ref(false);
	const btnLoadingType = ref("");
	const retryTimes = ref(0);

	let protocal = "";
	//如你的链接是wss:则修改为wxs:,如果你的链接是ws:则修改为wx:
	// #ifdef H5
	protocal = "ws"
	// #endif
	// #ifdef MP-WEIXIN
	protocal = "wx"
	// #endif
	const connection = reactive({
		// ws or wss
		protocol: protocal,
		host: "jqrjq.cn",
		// ws -> 8083; wss -> 8084
		port: 8083,
		clientId: "emqx_vue3_" + Math.random().toString(16).substring(2, 8),
		/**
		 * By default, EMQX allows clients to connect without authentication.
		 * https://docs.emqx.com/en/enterprise/v4.4/advanced/auth.html#anonymous-login
		 */
		username: "admin",
		password: "public",
		clean: true,
		connectTimeout: 30 * 1000, // ms
		reconnectPeriod: 4000, // ms
		// for more options and details, please refer to https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
	});
	

	const handleOnReConnect = () => {
		retryTimes.value += 1;
		if (retryTimes.value > 5) {
			try {
				client.value.end();
				initData();
				console.log("connection maxReconnectTimes limit, stop retry");
			} catch (error) {
				console.log("handleOnReConnect catch error:", error);
			}
		}
	};

	const createConnection = () => {
		try {
			const {
				protocol,
				host,
				port,
				...options
			} = connection;
			const connectUrl = `${protocol}://${host}:${port}/mqtt`;

			/**
			 * if protocol is "ws", connectUrl = "ws://broker.emqx.io:8083/mqtt"
			 * if protocol is "wss", connectUrl = "wss://broker.emqx.io:8084/mqtt"
			 * 
			 * /mqtt: MQTT-WebSocket uniformly uses /path as the connection path,
			 * which should be specified when connecting, and the path used on EMQX is /mqtt.
			 * 
			 * for more details about "mqtt.connect" method & options,
			 * please refer to https://github.com/mqttjs/MQTT.js#mqttconnecturl-options
			 */
			client.value = mqtt.connect(connectUrl, options);

			if (client.value.on) {
				// https://github.com/mqttjs/MQTT.js#event-connect
				client.value.on("connect", () => {
					btnLoadingType.value = "";

					console.log("connection successful");
				});

				// https://github.com/mqttjs/MQTT.js#event-reconnect
				client.value.on("reconnect", handleOnReConnect);

				// https://github.com/mqttjs/MQTT.js#event-error
				client.value.on("error", (error) => {
					console.log("connection error:", error);
				});

				// https://github.com/mqttjs/MQTT.js#event-message
				client.value.on("message", (topic, message) => {
					receivedMessages.value = receivedMessages.value.concat(
						message.toString()
					);
					listmsg.push({topic:topic,message:message.toString()})
					console.log(`received message: ${message} from topic: ${topic}`);

				
				});
			}
		} catch (error) {
			console.log("mqtt.connect error:", error);
		}
	};
	//连接
	const Connect=()=>{
	  createConnection();
	  client.value.subscribe("envs", () => {
	  		            console.log(`订阅了主题 envs`)
	  		        })
	}

	const Disconnect=()=>{
	  console.log("关闭")
	  client.connected=false;
	  client.value.end();
	  connection.currentState='DISCONNECTED';
	}
	onMounted(() => {
		// createConnection();

	})
</script>

<style>


</style>